package com.android.tnovoselec.travelassistant.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;

import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.actionbarsherlock.app.SherlockFragment;
import com.android.tnovoselec.travelassistant.Config;
import com.android.tnovoselec.travelassistant.R;
import com.android.tnovoselec.travelassistant.adapter.MeteoAdapter;
import com.android.tnovoselec.travelassistant.async.DownloadWeather;
import com.android.tnovoselec.travelassistant.dto.ForecastFavoritesDto;
import com.android.tnovoselec.travelassistant.dto.MeteoFavoritesDto;
import com.android.tnovoselec.travelassistant.dto.MeteoResultHolder;
import com.android.tnovoselec.travelassistant.view.HomeFeatureLayout;
import com.nth.android.common.async.Async;
import com.nth.android.common.async.listener.Outcome;
import com.nth.android.common.async.notif.NotifierFactory;
import com.nth.android.common.util.ApplicationUtil;
import com.nth.android.image.ImageDownloader;
import com.nth.android.ui.NTHViewPager;
import com.nth.android.ui.NTHViewPagerTab2;

/**
 * Title: Android Framework - Meteo <br />
 * <br />
 * Copyright: Copyright (c) 2011 <br />
 * <br />
 * NTH Company: NTH d.o.o. <br />
 * <br />
 * 
 * MeteoFragment class is used to handle {@link ViewPager} holding all the
 * weather data. It also changes it's own background depending on the current
 * weather situation. All the data is stored and read from database.
 * 
 * @author Tomislav Novoselec
 * @version 1.0.0
 * @since 1.0.0
 * 
 * 
 */
public class MeteoFragment extends SherlockFragment implements OnPageChangeListener {

	public static final Uri CONTENT_URI = Uri.parse("content://com.nth.android.media/meteo");
	protected static final String INITIALIZED = "initialized";
	public static final String EXTRA_CITY_ID = "extraCityId";

	protected static boolean FREE_RUN = false;

	Handler handler = new Handler();

	boolean firstTime = true;
	boolean downloadData = true;
	int viewPagerPosition = 0;
	String cityId = "";

	NTHViewPager mViewPager;
	ImageView background;
	ImageDownloader downloader;

	LinearLayout container;
	LayoutInflater inflater;
	ProgressDialog progressDialog;
	HomeFeatureLayout daysHorizontal;

	List<MeteoFavoritesDto> items;

	MeteoAdapter adapterNew;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		adapterNew = new MeteoAdapter(getActivity());

		if (!ApplicationUtil.isOnline(getActivity())) {
			// ImageToast.show(getActivity(), R.drawable.ic_error_icon,
			// R.string.meteo_error_download, Toast.LENGTH_LONG);
			return;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflaterF, ViewGroup containerF, Bundle savedInstanceState) {
		final View root = inflaterF.inflate(R.layout.meteo, containerF, false);

		downloader = ImageDownloader.getInstance();
		downloader.setExternalStorage(ApplicationUtil.getExternalStorage(getActivity().getApplicationContext()));
		((NTHViewPagerTab2) root.findViewById(R.id.meteo_viewpager_tab2)).bringToFront();

		mViewPager = (NTHViewPager) root.findViewById(R.id.meteo_viewpager);
		mViewPager.addOnPageChangeListener(this);
		mViewPager.setAdapter(adapterNew);

		background = (ImageView) root.findViewById(R.id.meteo_background);

		daysHorizontal = (HomeFeatureLayout) root.findViewById(R.id.meteo_bottom_bar);

		this.inflater = inflaterF;

		return root;
	}

	@Override
	public void onPageScrollStateChanged(int position) {
		// DO Nothing
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// DO Nothing
	}

	@Override
	public void onPageSelected(int position) {
		MeteoFavoritesDto meteoDto = items.get(position);
		List<ForecastFavoritesDto> forecasts = meteoDto.getForecastList();
		daysHorizontal.setFeatureItems((ArrayList<ForecastFavoritesDto>) forecasts);

		downloader.download(meteoDto.getBackgroundImageUrl(), background, true);
	}

	private void getMeteo() {
		progressDialog = ProgressDialog.show(getActivity(), getString(R.string.meteo_dialog_title), getString(R.string.meteo_dialog_message), true, false);

		Async.doAsync(null, new DownloadWeather(Config.METEO_URL, getActivity(), false), new Outcome<Void, Boolean>() {

			@Override
			protected void failed(Void key, Throwable t) {
				if (progressDialog != null && progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
				Log.e("Meteo failed!", "" + t.getMessage());
				t.printStackTrace();
			}

			@Override
			protected void succeeded(Void key, Boolean result) {
				if (progressDialog != null && progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
				populateUI();

			}
		}, NotifierFactory.newThreadSpecificNotifier(handler));
	}

	void populateUI() {

		List<MeteoFavoritesDto> meteos = MeteoResultHolder.getAll();

		items = meteos;

		adapterNew.setData(items);
		mViewPager.setAdapter(adapterNew);

		if (findPositionForCityId() != -1) {
			viewPagerPosition = findPositionForCityId();
			firstTime = false;
			cityId = null;
		}
		if (firstTime || viewPagerPosition == 0) {
			onPageSelected(viewPagerPosition);
			firstTime = false;
		} else {
			mViewPager.setCurrentItem(viewPagerPosition, true);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		getMeteo();
	}

	@Override
	public void onStop() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
		super.onStop();
	}

	public int findPositionForCityId() {
		if (TextUtils.isEmpty(cityId)) {
			return -1;
		}
		for (int i = 0; i < items.size(); i++) {
			MeteoFavoritesDto mfd = items.get(i);
			if (mfd.getCityId().equals(cityId)) {
				return i;
			}
		}
		return -1;
	}

}
